;
(function() {
  'use strict';
  angular.module('services.analysisSysOM.tradTime')
    .service('maxTradTimeService', maxTradTimeService);

  function maxTradTimeService($http, $filter, CoreService, $timeout) {
    var time = new Date();
    var date = new Date(time.getFullYear(), time.getMonth(), time.getDate() - 1); //页面时间默认当前日期的前一天
    //var date = new Date();
    //页面参数
    this.param = {
      businessLineCode: 0,
      businessLineName: '',
      tradTypeCode: [],
      tradTypeName: [],
      date: date
    };
    this.viewType = 'chart'; //视图类型
    this.showSearchPanel = true; //显示查询面板
    this.busLineList = []; //业务线列表
    this.dataList = []; //页面展示的数据列表集合
    var list = []; //处理表格数据的临时集合
    var dataList = []; //接收后端数据的集合
    var param = [];
    var tradTypeList = []; //业务线列表
    this.businessLineList = []; //业务线列表
    this.tradTypeList = []; //交易类型列表
    this.showIcon = true; //显示折线 表格图标选项
    this.showArrow = true; //控制查询面板箭头的显示和隐藏 
    var that = this;
    var chart = null;

    //隐藏查询面板
    this.hideSearchPanel = function() {
      this.showSearchPanel = false;
    };
    //清空页面旧值
    this.reset = function() {
      that.showSearchPanel = true;
      that.viewType = 'chart';
      that.param.date = date;
      tradTypeList = [];
      that.dataList = [];
    };

    //初始化页面下拉列表选项
    this.initSelectMenu = function() {
      //获取业务线
      $http.get('/sas/common/businessLineQuery')
        .then(function(res) {
          if (res.data.state === '10000') {
            that.businessLineList = res.data.data;
            that.param.businessLineCode = res.data.data[0].businessLineCode;
            //获取交易类型
            $http.post('/sas/analysisSysOM/sysPerformance/tradType/query', {
                businessCode: res.data.data[0].businessLineCode
              })
              .then(function(resType) {
                if (resType.data.state === '10000') {
                  that.tradTypeList = resType.data.data;
                  //that.param.tradTypeCode = [resType.data.data[0].tradCode];
                  that.param.tradTypeCode = [];
                  that.search();
                }
              }, function(resType) {});
          }
        }, function(res) {});
    };
    //根据业务线 联动 交易类型
    this.getTradType = function() {
      //获取交易类型
      $http.post('/sas/analysisSysOM/sysPerformance/tradType/query', {
          businessCode: that.param.businessLineCode
        })
        .then(function(resType) {
          if (resType.data.state === '10000' && resType.data) {
            that.tradTypeList = resType.data.data;
            //that.param.tradTypeCode = [resType.data.data[0].tradCode];
            that.param.tradTypeCode = [];
          }
        }, function(resType) {});
    };


    //查询最大交易耗时
    this.search = function() {
      if (!that.showSearchPanel) {
        that.showSearchPanel = true;
        return;
      }
      //根据Code获取Name
      var businessLine = that.businessLineList.filter(function(obj) {
        if (that.param.businessLineCode === obj.businessLineCode) {
          return obj;
        }
      })[0];
      that.param.businessLineName = businessLine.businessLineName;

      //如果交易类型选了选项 那么把所选项传给后台
      that.param.tradTypeCode.length || (that.param.tradTypeCode = that.tradTypeList);
      param = angular.copy(that.param);
      tradTypeList = angular.copy(that.tradTypeList);
      param.tradTypeCode = param.tradTypeCode.map(function(obj) {
        return obj.tradCode;
      });
      var tradType = [];
      angular.forEach(that.tradTypeList, function(obj) {
        if (param.tradTypeCode.indexOf(obj.tradCode) >= 0) {
          tradType.push(obj.tradName);
        }
      });
      param.tradTypeName = tradType;
      param.date = $filter('date')(param.date, 'yyyy-MM-dd');
      $http.post('/sas/analysisSysOM/sysPerformance/tradTime/maxTradTime/query', param)
        .then(function(res) {

          that.showSearchPanel = false;
          if (res.data.state === '10000' && res.data.data.length >= 1) {
            dataList = res.data.data;
            that.showArrow = true;
            that.param.tradTypeName = tradType;
            that.changeViewType();
            that.showIcon = true;
          } else if (res.data.data.length === 0) {
            that.PageDisplayStyle();
            CoreService.dialog('查询无数据');
          } else {
            that.PageDisplayStyle();
            CoreService.dialog('查询错误');
          }
        }, function(res) {});
    };

    this.changeViewType = function(type) {
      initChart();
      var ta = document.getElementById('ta');
      var cha = document.getElementById('cha');
      that.viewType = type || that.viewType;
      if (that.viewType === 'chart') {
        ta.style.backgroundColor = "";
        cha.style.backgroundColor = "#2196F3";
        setTimeout(initChart, 0);
      } else if (that.viewType === 'table') {
        ta.style.backgroundColor = "#2196F3";
        cha.style.backgroundColor = "";
        initTable();
      }
    };

    //初始化图表
    function initChart() {
      chart = echarts.init(document.getElementById('maxTradTimeChart'));
      //var lineName = that.dataList[0].businessLineName;
      var option = {
        animation: false,
        title: {
          text: $filter('date')(param.date, 'yyyy年MM月dd日') + param.businessLineName + param.tradTypeName + '最大交易耗时',
          x: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            var str = params[0].name;
            angular.forEach(params, function(param) {
              str += '<br/>' + param.seriesName + ': ' + param.value + ' ms';
            });
            return str;
          }
        },
        legend: {
          data: that.param.tradTypeName,
          x: 'right',
          y: 'center',
          orient: 'vertical'
        },
        xAxis: [{
          type: 'category',
          boundaryGap: false,
          data: [],
          splitLine: {
            show: false
          }
        }],
        yAxis: [{
          name: '交易耗时（ms）',
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }
        }],
        series: [],
        grid: {
          x: '104',
          x2: '128'
        }
      };

      var x = [];
      var time = 0;
      for (var i = 0; i <= 22; i++) {
        if (i <= 9) {
          time = '0' + i + ':00';
        } else {
          time = i + ':00';
        }
        x.push(time);
      }
      //如果是天猫业务线 则显示横轴时刻为23:00到22:00
      if (param.businessLineCode === '1') {
        x.unshift('23:00');
      } else {
        x.push('23:00');
      }
      option.xAxis[0].data = x;
      angular.forEach(param.tradTypeCode, function(tradCode) {
        var array = [];
        var time = 0;
        angular.forEach(dataList, function(obj) {
          angular.forEach(x, function(time) {
            if (obj.timeLine === time && obj.tradTypeCode === tradCode) {
              array.push(obj.maxTime);
            }
          });
        });

        var trad = tradTypeList.filter(function(obj) {
          if (tradCode === obj.tradCode) {
            return obj;
          }
        })[0];

        option.series.push({
          name: trad.tradName,
          type: 'line',
          data: array
        });
      });
      chart.setOption(option);
      $timeout(function() {
        that.onSubmit();
      }, 500);
    }

    //初始化表格
    function initTable() {
      list = [];
      that.title = $filter('date')(param.date, 'yyyy年MM月dd日') + param.businessLineName + param.tradTypeName.join(',') + '最大交易耗时';
      for (var i = 0; i <= 23; i++) {
        var date = '';
        if (i <= 9) {
          date = '0' + i + ':00';
        } else {
          date = i + ':00';
        }
        var row = [date, param.businessLineName];
        angular.forEach(param.tradTypeCode, function(code) {

          angular.forEach(dataList, function(obj) {
            if (obj.timeLine === date && obj.tradTypeCode === code) {
              row.push(obj.maxTime);
            }
          });
        });
        list.push(row);
      }
      that.dataList = list;
      //如果是天猫业务线 则显示横轴时刻为23:00到22:00
      if (param.businessLineCode === '1') {
        var row = that.dataList[that.dataList.length - 1];
        that.dataList.pop();
        that.dataList.unshift(row);
      }
    }

    //查询无数据时页面的样式
    this.PageDisplayStyle = function() {
      that.title = '';
      that.viewType = 'chart';
      that.showArrow = false;
      that.showSearchPanel = true; //显示查询面板
      that.showIcon = false; //隐藏表格和折线图标
      list = [];
      dataList = [];
      chart && chart.clear();
    }

    //导出excel
    this.sendData = {};
    this.onSubmit = function() {
      var data = {
        date: $filter('date')(param.date, 'yyyy-MM-dd'),
        base64s: [chart.getDataURL('png').split(',')[1]],
        title: $filter('date')(param.date, 'yyyy年MM月dd日') + param.businessLineName + param.tradTypeName.join(',') + '最大交易耗时',
        businessLineCode: param.businessLineCode,
        businessLineName: param.businessLineName,
        tradTypeCode: param.tradTypeCode,
        tradTypeName: param.tradTypeName
      };
      that.sendData = JSON.stringify(data);
    };
  }

  maxTradTimeService.$inject = ['$http', '$filter', 'CoreService', '$timeout'];
})();